package com.huanshi.security.config;


import com.huanshi.service.IRedisService;
import com.huanshi.utils.JwtTokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
@RequiredArgsConstructor
public class LogoutService implements LogoutHandler {
  @Resource
  private IRedisService redisServices;



  @Override
  public void logout(HttpServletRequest request,
                     HttpServletResponse response,
                     Authentication authentication) {
    final String authHeader = request.getHeader("Authorization");
    final String jwt;
    final Integer userId;
    if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
      return;
    }
    jwt = authHeader.substring(7);
    userId = JwtTokenUtil.getUserId(jwt);
    var storedToken = redisServices.del(String.valueOf(userId));
    SecurityContextHolder.clearContext();
  }
}
